<?php
namespace gnomephp\commands;


use Symfony\Component\Console\Input\InputArgument,
Symfony\Component\Console\Input\InputOption,
Symfony\Component\Console,
Doctrine\ORM\Tools\Console\MetadataFilter;

/**
 * Command to create a new application
 */
class CreateAppCommand extends Console\Command\Command
{
	/**
	 * @see Console\Command\Command
	 */
	protected function configure()
	{
		$this
		->setName('gnomephp:create')
		->setDescription('Creates a new application.')
		->setDefinition(array(
		new InputOption(
                'app-dir', null, InputOption::VALUE_REQUIRED,
                'Where should the application folder be created?',
            	GNOME_FW_PATH . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'apps' // Defaults to GnomePHP / apps dir.
            	),
            	new InputArgument(
                'app-name', InputArgument::REQUIRED,
                'The application name.'
                ),
                ))
                ->setHelp(<<<EOT
Generates proxy classes for entity classes.
EOT
                );
	}

	/**
	 * @see Console\Command\Command
	 */
	protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
	{


		$appName = $input->getArgument('app-name');
		if (!preg_match("/^[a-zA-Z_]+$/", $appName)){
			throw new \InvalidArgumentException(
			sprintf("The application name \"%s\" is not allowed. Allowed characters is A-Z , a-z and underscore.", $appName));
		}
		$destPath = $input->getOption('app-dir');
		if (!is_dir($destPath) || !$destPath){
			throw new \InvalidArgumentException(
			sprintf("The app directory %s does not exist. Please create the directory before proceeding.", $destPath));
		}

		switch(substr($destPath, strlen($destPath)-1, strlen($destPath))){
			case '/':
			case '\\':
				$destPath .= $appName;
				break;
			default:
				$destPath .= DIRECTORY_SEPARATOR.$appName;
				break;
		}

		// Create app dir.

		if ( ! is_dir($destPath)) {
			$output->write(PHP_EOL . 'Creating application directory.' . PHP_EOL);
			mkdir($destPath, 0777, true);
		}else{
			throw new \InvalidArgumentException(
			sprintf("Could not create application because the application already exists in %s.", $destPath));
		}

		// Copy resource files.
		$output->write('Copying application resources...' . PHP_EOL);
		$this->recursiveDirCopy('gnomephp'.DIRECTORY_SEPARATOR.'res'.DIRECTORY_SEPARATOR.'app', $destPath);

		
		$output->write('Rewriting variables...' . PHP_EOL);
		$controllerFile = $destPath . DIRECTORY_SEPARATOR . 'controller' . DIRECTORY_SEPARATOR . 'Application.php';
		file_put_contents($controllerFile, str_replace('__APP_NAME__', $appName, file_get_contents($controllerFile)));
		
		$gnomePhpPath = realpath('gnomephp');
		
		// Write app-data.php
		$output->write(sprintf('Writing app-data.php to %s', $destPath). PHP_EOL);
		file_put_contents(
			$destPath.DIRECTORY_SEPARATOR.'app-data.php',
			"<?php
				// This file was automatically generated by GnomePHP.
				// Include gnomephp framework engine. Change this if you have moved app directory.
				define('GNOME_FW_PATH', '$gnomePhpPath');

				// Define Application path to this app.
				define('GNOME_APP_PATH', dirname(__FILE__));

				define('GNOME_APP_NS', '$appName');

				// Include the bootstrap file. ( Autoloader ).
				require GNOME_FW_PATH.DIRECTORY_SEPARATOR.'bootstrap.php';

			
			"
		);
		

		$output->write('Your application "'.$appName.'" is now created to location: '.$destPath . PHP_EOL);
		$output->write('Thanks for using the PHP MVC Framework '.\gnomephp\Gnomephp::NAME.' v.'.\gnomephp\Gnomephp::getVersion().'. ' . PHP_EOL);


	}




	protected function recursiveDirCopy($src,$dst) {
		$dir = opendir($src);
		@mkdir($dst);
		while(false !== ( $file = readdir($dir)) ) {
			if (( $file != '.' ) && ( $file != '..' ) && $file != '.svn') {
				if ( is_dir($src . DIRECTORY_SEPARATOR . $file)) {
					$this->recursiveDirCopy($src . DIRECTORY_SEPARATOR . $file,$dst . DIRECTORY_SEPARATOR . $file);
				}
				else {
					copy($src . DIRECTORY_SEPARATOR . $file,$dst . DIRECTORY_SEPARATOR . $file);
            }
        }
    }
    closedir($dir);
} 
    
}